package com.example.mallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;
import com.example.mallproduct.controller.vo.AttrGroupWithAttrsVo;
import com.example.mallproduct.dao.AttrAttrgroupRelationDao;
import com.example.mallproduct.dao.AttrGroupDao;
import com.example.mallproduct.entity.AttrAttrgroupRelationEntity;
import com.example.mallproduct.entity.AttrEntity;
import com.example.mallproduct.entity.AttrGroupEntity;
import com.example.mallproduct.entity.CategoryEntity;
import com.example.mallproduct.service.AttrAttrgroupRelationService;
import com.example.mallproduct.service.AttrGroupService;
import com.example.mallproduct.service.AttrService;
import com.example.mallproduct.service.CategoryBrandRelationService;
import com.example.mallproduct.service.CategoryService;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 可以根据分类查询属性分组
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils infoByCatelogId(Map<String, Object> params) {

//        IPage<AttrGroupEntity> page = this.page(
//                new Query<AttrGroupEntity>().getPage(params),
//                new QueryWrapper<AttrGroupEntity>()
//        );
        QueryWrapper queryWrapper = new QueryWrapper<AttrGroupEntity>();
        if (!ObjectUtils.isEmpty(params.get("key"))) {
            queryWrapper.like("attr_group_name", params.get("key"));
        }
        if (!ObjectUtils.isEmpty(params.get("catelogId"))) {
            queryWrapper.eq("catelog_id", params.get("catelogId"));
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    queryWrapper
            );
            return new PageUtils(page);
        } else {
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    queryWrapper
            );
            return new PageUtils(page);
        }

    }


    @Autowired
    private CategoryService categoryService;

    /**
     * 获取到全部分类id
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public AttrGroupEntity catelogIdByGroupId(Long attrGroupId) {

        List<Long> catelogIds = Lists.newArrayListWithExpectedSize(3);
        AttrGroupEntity attrGroupEntity = this.getById(attrGroupId);

        CategoryEntity categoryEntity = categoryService.getById(attrGroupEntity.getCatelogId());
        getCatelogIds(categoryEntity, catelogIds);
        Collections.reverse(catelogIds);
        attrGroupEntity.setCatelogIds(catelogIds);
        return attrGroupEntity;
    }

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrService attrService;

    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private AttrGroupService attrGroupService;

    /**
     * 根据属性组编号查询对应的基础信息
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getAttrRelation(Long attrGroupId) {
        // 1. 根据属性组编号从 属性组和基本信息的关联表中查询出对应的属性信息
        List<AttrAttrgroupRelationEntity> list = attrAttrgroupRelationDao
                .selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        // 2.根据属性id数组获取对应的详情信息
        List<AttrEntity> attrEntities = list.stream()
                .map((entity) -> attrService.getById(entity.getAttrId()))
                .filter((entity) -> entity != null)
                .collect(Collectors.toList());
        return attrEntities;
    }

    /**
     * 递归获取分类id
     *
     * @param categoryEntity
     * @param catelogIds
     */
    public void getCatelogIds(CategoryEntity categoryEntity, List<Long> catelogIds) {
        catelogIds.add(categoryEntity.getCatId());
        if (0 != categoryEntity.getParentCid()) {
            getCatelogIds(categoryService.getById(categoryEntity.getParentCid()), catelogIds);
        }
    }

    /**
     * 删除关联
     *
     * @param attrGroupEntityList
     */
    @Override
    public void relationDelete(List<AttrGroupEntity> attrGroupEntityList) {
        List<AttrAttrgroupRelationEntity> list = attrGroupEntityList.stream().map(item -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.removeBatchRelation(list);
    }

    /**
     * 根据属性组编号查询对应的基础信息
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long attrgroupId) {
        // 1.查询当前属性组所在的类别编号
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupId);
        // 获取到对应的分类id
        Long catelogId = attrGroupEntity.getCatelogId();
        // 2.当前分组只能关联自己所属的类别下其他的分组没有关联的属性信息。
        // 先找到这个类别下的所有的分组信息
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        // 获取属性组的编号集合
        List<Long> groupIds = group.stream().map((g) -> g.getAttrGroupId()).collect(Collectors.toList());
        // 然后查询出类别信息下所有的属性组已经分配的属性信息
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> attrIds = relationEntities.stream().map((m) -> m.getAttrId()).collect(Collectors.toList());
        // 根据类别编号查询所有的属性信息并排除掉上面的属性信息即可
        // 这其实就是需要查询出最终返回给调用者的信息了  分页  带条件查询
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                // 查询的是基本属性信息，不需要查询销售属性信息
                .eq("attr_type", 1);
        // 然后添加排除的条件
        if (attrIds != null && attrIds.size() > 0) {
            wrapper.notIn("attr_id", attrIds);
        }
        // 还有根据key的查询操作
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        // 查询对应的相关信息
        IPage<AttrEntity> page = attrService.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    /**
     * 批量保存关联
     *
     * @param attrGroupEntityList
     */
    @Override
    public void saveBatchAttrRelation(List<AttrGroupEntity> attrGroupEntityList) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrGroupEntityList.stream().map(item -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationService.saveBatch(attrAttrgroupRelationEntities);
    }

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 根据三级分类的编号查询出对应的所有属性组
     * 根据属性组查询对应的属性信息
     *
     * @param catelogId
     */
    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrs(Long catelogId) {
        //根据三级分类的编号查询出对应的所有属性组
        List<AttrGroupEntity> attrGroupEntityList = this.list(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        List<AttrGroupWithAttrsVo> attrGroupWithAttrsVos = attrGroupEntityList.stream().map(attrGroupEntity -> {
            AttrGroupWithAttrsVo attrGroupWithAttrsVo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(attrGroupEntity, attrGroupWithAttrsVo);
            //根据属性组查询对应的属性信息
            List<AttrEntity> attrEntityList = getAttrRelation(attrGroupEntity.getAttrGroupId());
            attrGroupWithAttrsVo.setAttrs(attrEntityList);
            return attrGroupWithAttrsVo;
        }).collect(Collectors.toList());
        return attrGroupWithAttrsVos;
    }
}